package com.it.schoolbookshop_back.controller;

import com.it.schoolbookshop_back.entities.po.Notification;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.enums.NotificationType;
import com.it.schoolbookshop_back.service.NotificationService;
import com.it.schoolbookshop_back.utils.UserContext;
import com.it.schoolbookshop_back.entities.dto.TransactionNotificationDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通知控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/notifications")
public class NotificationController {
    
    @Autowired
    private NotificationService notificationService;
    
    /**
     * 获取当前用户的所有通知
     * 
     * @return 通知列表
     */
    @GetMapping
    public Result<List<Notification>> getNotifications() {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        List<Notification> notifications = notificationService.getUserNotifications(userId);
        return Result.success(notifications);
    }
    
    /**
     * 获取当前用户特定类型的通知
     * 
     * @param type 通知类型
     * @return 通知列表
     */
    @GetMapping("/type/{type}")
    public Result<List<Notification>> getNotificationsByType(@PathVariable String type) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        NotificationType notificationType = NotificationType.fromString(type);
        if (notificationType == null) {
            return Result.validateFailed("无效的通知类型");
        }
        
        List<Notification> notifications = notificationService.getUserNotificationsByType(userId, notificationType);
        return Result.success(notifications);
    }
    
    /**
     * 标记通知为已读
     * 
     * @param notificationId 通知ID
     * @return 操作结果
     */
    @PutMapping("/read/{id}")
    public Result<String> markAsRead(@PathVariable("id") Integer notificationId) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        boolean success = notificationService.markAsRead(notificationId);
        if (success) {
            return Result.success("标记已读成功");
        } else {
            return Result.failed("标记已读失败");
        }
    }
    
    /**
     * 标记所有通知为已读
     * 
     * @return 操作结果
     */
    @PutMapping("/read/all")
    public Result<String> markAllAsRead() {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        boolean success = notificationService.markAllAsRead(userId);
        if (success) {
            return Result.success("标记全部已读成功");
        } else {
            return Result.failed("标记全部已读失败");
        }
    }
    
    /**
     * 获取未读通知数量
     * 
     * @return 未读通知数量
     */
    @GetMapping("/unread/count")
    public Result<Map<String, Object>> getUnreadCount() {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        // 获取总未读数和各类型未读数
        int totalCount = notificationService.getUnreadCount(userId);
        int messageCount = notificationService.getUnreadCountByType(userId, NotificationType.MESSAGE);
        int favoriteCount = notificationService.getUnreadCountByType(userId, NotificationType.FAVORITE);
        int transactionCount = notificationService.getUnreadCountByType(userId, NotificationType.TRANSACTION);
        
        Map<String, Object> countsMap = new HashMap<>();
        countsMap.put("total", totalCount);
        countsMap.put("message", messageCount);
        countsMap.put("favorite", favoriteCount);
        countsMap.put("transaction", transactionCount);
        
        return Result.success(countsMap);
    }
    
    /**
     * 删除通知
     * 
     * @param notificationId 通知ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteNotification(@PathVariable("id") Integer notificationId) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        // TODO: 验证通知所属用户
        boolean success = notificationService.deleteNotification(notificationId);
        if (success) {
            return Result.success("删除通知成功");
        } else {
            return Result.failed("删除通知失败");
        }
    }
    
    /**
     * 创建交易通知 - 在交易支付完成后调用
     * 向卖家发送交易通知，告知其有新的交易完成
     * 
     * @param notificationDTO 交易通知请求DTO
     * @return 操作结果
     */
    @PostMapping("/transaction")
    public Result<String> createTransactionNotification(@RequestBody TransactionNotificationDTO notificationDTO) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        // 请求参数校验
        if (notificationDTO == null) {
            return Result.validateFailed("请求参数不能为空");
        }
        
        if (notificationDTO.getSellerId() == null) {
            return Result.validateFailed("卖家ID不能为空");
        }
        
        if (notificationDTO.getTransactionId() == null) {
            return Result.validateFailed("交易ID不能为空");
        }
        
        if (notificationDTO.getBookTitle() == null || notificationDTO.getBookTitle().isEmpty()) {
            return Result.validateFailed("书籍标题不能为空");
        }
        
        try {
            // 构建通知内容
            String notificationContent = "您的图书《" + notificationDTO.getBookTitle() + "》已被购买，交易已完成";
            
            // 创建通知(无论卖家是否开启了交易通知，都会保存到数据库)
            boolean success = notificationService.createNotification(
                notificationDTO.getSellerId(),
                NotificationType.TRANSACTION,
                notificationContent,
                notificationDTO.getTransactionId()
            );
            
            if (success) {
                log.info("已为卖家(ID:{})创建交易通知，交易ID:{}，书籍:{}",
                    notificationDTO.getSellerId(), notificationDTO.getTransactionId(), notificationDTO.getBookTitle());
                return Result.success("交易通知创建成功");
            } else {
                return Result.failed("交易通知创建失败");
            }
        } catch (Exception e) {
            log.error("创建交易通知失败", e);
            return Result.failed("创建交易通知失败: " + e.getMessage());
        }
    }
} 